import {
  LOGIN_START,
  LOGIN_SUCCESS,
  LOGIN_FAIL
} from '../action/actionTypes'

let initState = { //默认值 ， 假设未登录
  isLoading:false,
  isLogin:false,
  userInfo:null
}

//尝试提取本地存储用户信息，初始化正确的登录状态
let info = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
if(info){
  initState.userInfo = JSON.parse(info)
  initState.isLogin = true
}

export default function(state=initState,action){
  switch (action.type) {
    case LOGIN_START:  //开始登录
      state.isLoading = true
      return {...state}
    case LOGIN_SUCCESS: //登录成功
      state.isLoading = false
      state.isLogin = true
      state.userInfo = action.payload //此处的payload是用户信息
      let info = JSON.stringify(action.payload)
      if(action.remember){
        localStorage.setItem('userInfo',info)  //记住密码
      }else{
        sessionStorage.setItem('userInfo',info)
      }
      return {...state}
    case LOGIN_FAIL:  //登录失败、退出登录
      state.isLoading = false
      state.isLogin = false
      state.userInfo = null
      localStorage.removeItem('userInfo')
      sessionStorage.removeItem('userInfo')
      return {...state}
    default:
      return state
  }
}